# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: xguo

import coin.exchange.base.kr_rest.public_client_base as pubcb
from coin.exchange.fcoin.kr_rest.native_public_client import FcoinNativePublicClient
from coin.exchange.fcoin.kr_rest.constants import active_symbol_list
from coin.exchange.fcoin.kr_rest.product import FcoinProduct
from coin.exchange.base.kr_rest.rest_client_base import RestUpdate

from coin.proto.coin_market_query_pb2 import ProductTicker, ExchangeTicker


class FcoinFeedParser(object):
  @staticmethod
  def parse_native_ticker(update_msg, product):
    field_names = ('last_price',
                   'last_qty',
                   'bid0_price',
                   'bid0_qty',
                   'ask0_price',
                   'ask0_qty',
                   'place_holder0',
                   'high',
                   'low',
                   'place_holder1',
                   'place_holder2')
    assert update_msg['status'] == 0, update_msg
    ticker = dict(zip(field_names, update_msg['data']['ticker']))
    return ProductTicker(ask=float(ticker['ask0_price']),
                         bid=float(ticker['bid0_price']),
                         last=float(ticker['last_price']),
                         high=float(ticker['high']),
                         low=float(ticker['low']),
                         native_symbol=product.native_symbol,
                         symbol=product.symbol)

  @staticmethod
  def parse_exchange_ticker(msg_list):
    product_ticker_list = []
    for update_msg in msg_list:
      native_symbol = update_msg['data']['type'].split('.')[1]
      product = FcoinProduct.FromStr(native_symbol)
      product_ticker_list.append(FcoinFeedParser.parse_native_ticker(update_msg, product))
    assert len(product_ticker_list) > 0
    return ExchangeTicker(exchange='Fcoin', each_ticker=product_ticker_list)


class FcoinPublicClient(pubcb.PublicClientBase):
  def __init__(self, timeout=5):
    self.npubc = FcoinNativePublicClient(timeout=timeout)

  def query_ticker_impl(self, product):
    update = self.npubc.get_ticker(product.native_symbol)
    update.msg = FcoinFeedParser.parse_native_ticker(update.msg, product)
    return update

  def query_exchange_ticker_impl(self):
    req_timestamp = None
    msg_list = []
    for native_symbol in active_symbol_list:
      single_update = self.npubc.get_ticker(native_symbol)
      if req_timestamp is None:
        req_timestamp = single_update.req_timestamp
      msg_list.append(single_update.msg)
    res_timestamp = single_update.res_timestamp
    update = RestUpdate(req_timestamp, res_timestamp, msg_list)
    update.msg = FcoinFeedParser.parse_exchange_ticker(update.msg)
    return update

  def query_level_book_impl(self, product):
    # Not useful.
    raise NotImplementedError()
